import type { Value } from '@udecode/plate'

import {
  BasicMarksPlugin,
  CodePlugin,
  StrikethroughPlugin,
} from '@udecode/plate-basic-marks/react'
import { BasicElementsPlugin } from '@udecode/plate-basic-elements/react'

import {
  type PlateElementProps,
  type PlateLeafProps,
  ParagraphPlugin,
  Plate,
  PlateElement,
  PlateLeaf,
  usePlateEditor,
} from '@udecode/plate/react'
import { all, createLowlight } from 'lowlight'
import { LinkPlugin } from '@udecode/plate-link/react'

import { Editor, EditorContainer } from '@/components/ui/editor'
import { FixedToolbar } from '@/components/ui/fixed-toolbar'
import { MarkToolbarButton } from '@/components/ui/mark-toolbar-button'
import { BlockquoteElement } from '@/components/ui/blockquote-element'
import { ParagraphElement } from '@/components/ui/paragraph-element'
import { ToolbarButton, ToolbarGroup } from '@/components/ui/toolbar'
import { HeadingElement } from '@/components/ui/heading-element'
import { alignPlugin } from './plugins/align-plugin'
import { AlignDropdownMenu } from '@/components/ui/align-dropdown-menu'
import { CodeBlockElement } from '@/components/ui/code-block-element'
import { CodeLeaf } from '@/components/ui/code-leaf'
import { CodeLineElement } from '@/components/ui/code-line-element'
import { CodeSyntaxLeaf } from '@/components/ui/code-syntax-leaf'
import { FontSizeToolbarButton } from '@/components/ui/font-size-toolbar-button'
import { TurnIntoDropdownMenu } from '@/components/ui/turn-into-dropdown-menu'
// import { ListIndentToolbarButton } from '@/components/ui/list-indent-toolbar-button'
import { ColumnPlugin, ColumnItemPlugin } from '@udecode/plate-layout/react'

import {
  ListPlugin,
  BulletedListPlugin,
  NumberedListPlugin,
  ListItemPlugin,
  TodoListPlugin,
} from '@udecode/plate-list/react'
import { IndentListPlugin } from '@udecode/plate-indent-list/react'

import {
  CodeBlockPlugin,
  CodeLinePlugin,
  CodeSyntaxPlugin,
} from '@udecode/plate-code-block/react'
import {
  BaselineIcon,
  BoldIcon,
  Code2Icon,
  ItalicIcon,
  PaintBucketIcon,
  Redo2Icon,
  StrikethroughIcon,
  UnderlineIcon,
  Undo2Icon,
} from 'lucide-react'
import { IndentPlugin } from '@udecode/plate-indent/react'
import { BlockquotePlugin } from '@udecode/plate-block-quote/react'
import { HEADING_LEVELS } from '@udecode/plate-heading'
// import { FireLiComponent, FireMarker } from '@/components/ui/indent-fire-marker'
import { withProps } from '@udecode/cn'
import { TodoListElement } from '@/components/ui/todo-list-element'
import { ListElement } from '@/components/ui/list-element'
import { ListToolbarButton } from '@/components/ui/list-toolbar-button'
import { IndentTodoToolbarButton } from '@/components/ui/indent-todo-toolbar-button'
import { LinkFloatingToolbar } from '@/components/ui/link-floating-toolbar'
import { ColorDropdownMenu } from '@/components/ui/color-dropdown-menu'
import { LinkToolbarButton } from '@/components/ui/link-toolbar-button'
import { ToggleToolbarButton } from '@/components/ui/toggle-toolbar-button'
// import { ExportToolbarButton } from '@/components/ui/export-toolbar-button'
import {
  FontBackgroundColorPlugin,
  FontColorPlugin,
  FontSizePlugin,
} from '@udecode/plate-font/react'
import { ExitBreakPlugin } from '@udecode/plate-break/react'

import { HighlightPlugin } from '@udecode/plate-highlight/react'
import { markdownPlugin } from './plugins/markdown-plugin'
import { HighlightLeaf } from '@/components/ui/highlight-leaf'
import {
  TableCellHeaderPlugin,
  TableCellPlugin,
  TablePlugin,
  TableRowPlugin,
} from '@udecode/plate-table/react'
import { NodeIdPlugin } from '@udecode/plate-node-id'
import { DndPlugin } from '@udecode/plate-dnd'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import { autoformatListPlugin } from './plugins/auto-format-plugin'
import {
  TableCellElement,
  TableCellHeaderElement,
} from '@/components/ui/table-cell-element'
import { TableElement } from '@/components/ui/table-element'
import { TableRowElement } from '@/components/ui/table-row-element'
import { TableDropdownMenu } from '@/components/ui/table-dropdown-menu'
import { EmojiPlugin } from '@udecode/plate-emoji/react'
import emojiMartData from '@emoji-mart/data'
import { EmojiDropdownMenu } from '@/components/ui/emoji-dropdown-menu'
import {
  AudioPlugin,
  FilePlugin,
  ImagePlugin,
  MediaEmbedPlugin,
  PlaceholderPlugin,
  VideoPlugin,
} from '@udecode/plate-media/react'
import { ImageElement } from '@/components/ui/image-element'
import { MediaVideoElement } from '@/components/ui/media-video-element'
import { MediaFileElement } from '@/components/ui/media-file-element'
import { MediaAudioElement } from '@/components/ui/media-audio-element'
import { MediaPlaceholderElement } from '@/components/ui/media-placeholder-element'
import { MediaEmbedElement } from '@/components/ui/media-embed-element'
import { mediaPlugins } from './plugins/media-plugin'
import { MediaToolbarButton } from '@/components/ui/media-toolbar-button'
import { TogglePlugin } from '@udecode/plate-toggle/react'
import { ToggleElement } from '@/components/ui/toggle-element'
import { FireLiComponent, FireMarker } from '@/components/ui/indent-fire-marker'
import { TodoLi, TodoMarker } from '@/components/ui/indent-todo-marker'
import { ColumnGroupElement } from '@/components/ui/column-group-element'
import { ColumnElement } from '@/components/ui/column-element'
import { dndPlugins } from './plugins/dnf-plugin'

const initialValue: Value = [
  {
    type: 'p',
    children: [
      { text: 'Hello! Try out the ' },
      { text: 'bold', bold: true },
      { text: ', ' },
      { text: 'italic', italic: true },
      { text: ', and ' },
      { text: 'underline', underline: true },
      { text: ' formatting.' },
    ],
  },
]
const lowlight = createLowlight(all)
export interface EditorProps {
  onChange?: (value: Value) => void
  value?: Value
  placeholder?: string
}
export default function App(props: EditorProps) {
  const editor = usePlateEditor({
    plugins: [
      BasicMarksPlugin,
      BasicElementsPlugin,
      alignPlugin,
      StrikethroughPlugin,
      CodeBlockPlugin.configure({ options: { lowlight } }),
      IndentPlugin.extend({
        inject: {
          targetPlugins: [
            ParagraphPlugin.key,
            ...HEADING_LEVELS,
            BlockquotePlugin.key,
            CodeBlockPlugin.key,
            TogglePlugin.key,
          ],
        },
      }),
      IndentListPlugin.extend({
        inject: {
          targetPlugins: [
            ParagraphPlugin.key,
            ...HEADING_LEVELS,
            BlockquotePlugin.key,
            CodeBlockPlugin.key,
            TogglePlugin.key,
          ],
        },
        options: {
          listStyleTypes: {
            fire: {
              liComponent: FireLiComponent,
              markerComponent: FireMarker,
              type: 'fire',
            },
            todo: {
              liComponent: TodoLi,
              markerComponent: TodoMarker,
              type: 'todo',
            },
          },
        },
      }),
      ExitBreakPlugin.configure({
        options: {
          rules: [
            {
              hotkey: 'mod+enter',
            },
            {
              hotkey: 'mod+shift+enter',
              before: true,
            },
            {
              hotkey: 'enter',
              query: {
                start: true,
                end: true,
                allow: [
                  ...HEADING_LEVELS,
                  ListPlugin.key,
                  BlockquotePlugin.key,
                  CodeBlockPlugin.key,
                ],
              },
              relative: true,
              level: 1,
            },
          ],
        },
      }),
      NodeIdPlugin,
      TogglePlugin,
      ListPlugin,
      TodoListPlugin,
      // BulletedListPlugin,
      // NumberedListPlugin,
      ColumnPlugin,
      ...dndPlugins,
      FontColorPlugin,
      FontBackgroundColorPlugin,
      FontSizePlugin,
      HighlightPlugin,
      markdownPlugin,
      autoformatListPlugin,
      TablePlugin.configure({
        options: {
          initialTableWidth: 600,
        },
      }),
      NodeIdPlugin,
      LinkPlugin.configure({
        render: { afterEditable: () => <LinkFloatingToolbar /> },
      }),
      DndPlugin.configure({ options: { enableScroller: true } }),
      EmojiPlugin.configure({
        options: { data: emojiMartData as emojiMartData.EmojiMartData },
      }),
      ...mediaPlugins,
    ],

    value: initialValue,
    components: {
      bold: (props: PlateLeafProps) => <PlateLeaf {...props} as="strong" />,
      italic: (props: PlateLeafProps) => <PlateLeaf {...props} as="em" />,
      underline: (props: PlateLeafProps) => <PlateLeaf {...props} as="u" />,
      h1: (props: PlateElementProps) => (
        <HeadingElement {...props} variant="h1" />
      ),
      h2: (props: PlateElementProps) => (
        <HeadingElement {...props} variant="h2" />
      ),
      h3: (props: PlateElementProps) => (
        <HeadingElement {...props} variant="h3" />
      ),
      h4: (props: PlateElementProps) => (
        <HeadingElement {...props} variant="h4" />
      ),
      h5: (props: PlateElementProps) => (
        <HeadingElement {...props} variant="h5" />
      ),
      h6: (props: PlateElementProps) => (
        <HeadingElement {...props} variant="h6" />
      ),
      blockquote: BlockquoteElement,
      p: ParagraphElement,
      strikethrough: (props: PlateLeafProps) => <PlateLeaf {...props} as="s" />,
      align: AlignDropdownMenu, // 使用 AlignDropdownMenu 作为 align 的组件
      [CodeBlockPlugin.key]: CodeBlockElement, // 处理整个代码块容器
      [CodeLinePlugin.key]: CodeLineElement, // 处理代码行
      [CodePlugin.key]: CodeLeaf, // 处理代码行内的代码
      [CodeSyntaxPlugin.key]: CodeSyntaxLeaf, // 处理代码语法高亮
      [BulletedListPlugin.key]: withProps(ListElement, { variant: 'ul' }),
      [ListItemPlugin.key]: withProps(PlateElement, { as: 'li' }),
      [NumberedListPlugin.key]: withProps(ListElement, { variant: 'ol' }),
      [TodoListPlugin.key]: TodoListElement,
      [ColumnItemPlugin.key]: ColumnElement,
      [ColumnPlugin.key]: ColumnGroupElement,
      [HighlightPlugin.key]: HighlightLeaf,
      [TableCellHeaderPlugin.key]: TableCellHeaderElement,
      [TableCellPlugin.key]: TableCellElement,
      [TablePlugin.key]: TableElement,
      [TableRowPlugin.key]: TableRowElement,
      [TogglePlugin.key]: ToggleElement,
      [ImagePlugin.key]: ImageElement,
      [VideoPlugin.key]: MediaVideoElement,
      [AudioPlugin.key]: MediaAudioElement,
      [FilePlugin.key]: MediaFileElement,
      [MediaEmbedPlugin.key]: MediaEmbedElement,
      [PlaceholderPlugin.key]: MediaPlaceholderElement,
    },
  })
  return (
    <div className="border border-gray-300 rounded-md max-w-5xl  mt-10">
      <DndProvider backend={HTML5Backend}>
        <Plate
          editor={editor}
          onChange={({ value }) => {
            if (props.onChange) {
              props.onChange(value)
            }
          }}
        >
          <FixedToolbar className="justify-start ">
            <ToolbarGroup>
              <ToolbarButton
                onClick={() => editor.tf.undo()}
                tooltip="Undo (⌘+Z)"
              >
                <Undo2Icon />
              </ToolbarButton>
              <ToolbarButton
                onClick={() => editor.tf.redo()}
                tooltip="Redo (⌘+⇧+Z)"
              >
                <Redo2Icon />
              </ToolbarButton>
            </ToolbarGroup>
            {/* <ToolbarGroup>
              <ExportToolbarButton />
            </ToolbarGroup> */}
            <ToolbarGroup>
              <TurnIntoDropdownMenu />
              <FontSizeToolbarButton />
            </ToolbarGroup>
            <ToolbarGroup>
              <MarkToolbarButton nodeType="bold" tooltip="Bold (⌘+B)">
                <BoldIcon />
              </MarkToolbarButton>
              <MarkToolbarButton nodeType="italic" tooltip="Italic (⌘+I)">
                <ItalicIcon />
              </MarkToolbarButton>
              <MarkToolbarButton nodeType="underline" tooltip="Underline (⌘+U)">
                <UnderlineIcon />
              </MarkToolbarButton>

              <MarkToolbarButton
                nodeType="strikethrough"
                tooltip="Strikethrough (⌘+⇧+M)"
              >
                <StrikethroughIcon />
              </MarkToolbarButton>

              <MarkToolbarButton nodeType={CodePlugin.key} tooltip="Code (⌘+E)">
                <Code2Icon />
              </MarkToolbarButton>

              <ColorDropdownMenu
                nodeType={FontColorPlugin.key}
                tooltip="Text color"
              >
                <BaselineIcon />
              </ColorDropdownMenu>

              <ColorDropdownMenu
                nodeType={FontBackgroundColorPlugin.key}
                tooltip="Background color"
              >
                <PaintBucketIcon />
              </ColorDropdownMenu>
            </ToolbarGroup>
            <ToolbarGroup>
              <AlignDropdownMenu />
              <ListToolbarButton nodeType={BulletedListPlugin.key} />
              <ListToolbarButton nodeType={NumberedListPlugin.key} />
              <IndentTodoToolbarButton />
              {/* <ListIndentToolbarButton /> */}
              <ToggleToolbarButton />
            </ToolbarGroup>
            <ToolbarGroup>
              <LinkToolbarButton />

              <TableDropdownMenu />
              <EmojiDropdownMenu />
            </ToolbarGroup>
            <ToolbarGroup>
              <MediaToolbarButton nodeType={ImagePlugin.key} />
              {/* <MediaToolbarButton nodeType={VideoPlugin.key} />
              <MediaToolbarButton nodeType={AudioPlugin.key} /> */}
              <MediaToolbarButton nodeType={FilePlugin.key} />
              {/* <MediaToolbarButton nodeType={MediaEmbedPlugin.key} /> */}
            </ToolbarGroup>
          </FixedToolbar>
          <EditorContainer>
            <Editor placeholder={props.placeholder || ''} />
          </EditorContainer>
        </Plate>
      </DndProvider>
    </div>
  )
}
